import CharacterCard from './CharacterCard.js';
import apiService from '../../utils/api.js';

class CharacterPanel {
  constructor(onAddCharacter, onSelectCharacter) {
    this.characterList = document.createElement('div');
    this.addButton = document.createElement('button');
    this.onAddCharacter = onAddCharacter;
    this.onSelectCharacter = onSelectCharacter;
    this.characters = [];
    this.currentCharacterIndex = -1;
    this.setupEventListeners();
  }

  getCurrentCharacter() {
    if (this.currentCharacterIndex >= 0 &&
      this.currentCharacterIndex < this.characters.length) {
      return this.characters[this.currentCharacterIndex].getData();
    }
    return null;
  }



  setupEventListeners() {
    this.addButton.addEventListener('click', this.onAddCharacter);
  }

  addCharacter(characterData) {
    // 仅在有效数据时创建卡片
    if (characterData && Object.keys(characterData).length > 0) {
      const characterCard = new CharacterCard(characterData, (character) => {
        // 根据角色索引切换选项卡
        const index = this.characters.indexOf(characterCard);
        this.currentCharacterIndex = index;
        this.onSelectCharacter(character, index);
      });
      this.characters.push(characterCard);
      const renderedCard = characterCard.render();
      if (renderedCard) {
        // 确保角色列表容器存在
        if (!this.characterList.parentElement) {
          const container = this.characterList.closest('.character-panel-container') ||
                           document.querySelector('.character-panel-container');
          if (container) {
            container.insertBefore(this.characterList, this.addButton);
          }
        }
        // 添加新角色
        this.characterList.appendChild(renderedCard);
      }
    }
  }

  updateCharacter(index, characterData) {
    if (index >= 0 && index < this.characters.length) {
      this.characters[index].update(characterData);
    }
  }

  render() {
    const container = document.createElement('div');
    container.classList.add('character-panel-container');



    // 添加新增角色按钮
    this.addButton.textContent = '+ 添加角色';
    this.addButton.classList.add('add-character-button');
    container.appendChild(this.addButton);

    return container;
  }
}

export default CharacterPanel;
